import 'package:dartx/dartx.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:gluz/app/data/api_response.dart';
import 'package:gluz/app/data/shop/shop_cart_entity.dart';
import 'package:gluz/app/data/shop/shop_detail_entity.dart';
import 'package:gluz/app/data/shop/shop_evaluate_entity.dart';
import 'package:gluz/app/routes/app_pages.dart';
import 'package:gluz/app/utils/toast_util.dart';

import '../../../../../app_session.dart';
import '../../../../utils/http_util.dart';
import '../../../../utils/network/http_manager.dart' as dio;
import 'product_spec_modal_controller.dart';
import '../views/product_spec_modal_view.dart';

class ProductDetailController extends GetxController
    with GetTickerProviderStateMixin {
  String productId = '';
  // 商品数据
  ShopDetailEntity? shopDetailEntity;
  ShopDetailDetail? shopDetailDetail;

  // 轮播图控制器
  late PageController bannerController;
  // 当前轮播图索引
  final RxInt currentBannerIndex = 0.obs;

  // 商品图片/视频列表
  final RxList<ShopDetailImages> mediaList = <ShopDetailImages>[].obs;

  // 商品3D展示图片列表
  final RxList<ShopDetailImages> product3DImages = <ShopDetailImages>[].obs;

  // Tab控制器
  late TabController tabController;

  // 商品讲解悬浮窗显示状态
  final RxBool isExplanationVisible = true.obs;

  // 当前选中的评价类型
  final RxString selectedReviewType = '好评'.obs;

  // 是否收藏
  final RxBool isFavorited = false.obs;

  // 商品参数列表
  final RxList<Map<String, String>> productSpecs = <Map<String, String>>[].obs;

  // 购物车列表
  final RxList<ShopCartEntity> cartList = <ShopCartEntity>[].obs;

  // 用户评价列表
  final RxList<ShopEvaluateEntity> evaluateList = <ShopEvaluateEntity>[].obs;

  @override
  void onInit() {
    super.onInit();

    // 初始化控制器
    bannerController = PageController();
    tabController = TabController(length: 2, vsync: this);

    // 监听Tab切换
    tabController.addListener(() {
      update(); // 更新UI
    });

    // 获取商品数据
    _loadProductData();
    // 获取商品类目,获取商品规格
    _loadProductParam();
    // 获取购物车列表
    _loadProductCartList();
    // 获取评价列表
    _loadEvaluateList();
  }

  @override
  void onClose() {
    bannerController.dispose();
    tabController.dispose();
    super.onClose();
  }

  // 加载商品数据
  Future<void> _loadProductData() async {
    // 从参数获取商品ID
    productId = Get.arguments as String;

    ToastUtil.showLoading();
    shopDetailEntity = await app.http.request(
      path: '/api/mall/getProductInfo',
      params: {'productId': productId},
      fromJson: (e) => ShopDetailEntity.fromJson(Map<String, dynamic>.from(e)),
    );
    shopDetailDetail = shopDetailEntity?.detail.first;
    ToastUtil.dismiss();
    _initSubData();
    update();
  }

  // 初始化模拟数据
  void _initSubData() {
    mediaList.value = shopDetailEntity?.images ?? [];

    // 3D展示图片
    product3DImages.value = shopDetailEntity?.images ?? [];

    double productWeight = (shopDetailDetail?.weight ?? '0').toDouble();
    double productVolume = (shopDetailDetail?.unitVolume ?? '1').toDouble();
    double productDensity = productWeight / productVolume;
    // 商品参数
    productSpecs.value = [
      {'品名': shopDetailEntity?.skuName ?? '-'},
      {'品牌': shopDetailEntity?.brandName ?? '-'},
      {'数量单位': shopDetailDetail?.saleUnit ?? '-'},
      {'单品重量': productWeight.toString()},
      {'单品密度': '${productDensity.toStringAsFixed(2)}kg/m³'},
      {'单品体积': productVolume.toString()},
      {'商品颜色': shopDetailDetail?.productColor ?? '-'},
      {'货物类型': shopDetailEntity?.saleModelString() ?? '-'},
      {'起卖数量': shopDetailEntity?.minOrderQuantity ?? '-'},
      {'起批数量': shopDetailEntity?.lowestBuy.toString() ?? '-'},
    ];
  }

  // 获取商品类目,获取商品规格
  Future<void> _loadProductParam() async {}
  // 获取购物车列表
  Future<void> _loadProductCartList() async {
    cartList.value =
        await app.http.request(
          path: '/api/carriage/shoppingCartList',
          params: {'pageSize': 100, 'pageNum': 0},
          fromJson: (e) {
            List listMap = e['records'];
            return listMap.map((obj) {
              return ShopCartEntity.fromJson(Map<String, dynamic>.from(obj));
            }).toList();
          },
        ) ??
        [];
  }

  Future<void> _loadEvaluateList() async {
    evaluateList.value =
        await app.http.request(
          path: '/api/mall/getProductReviewList',
          params: {'productId': productId, 'pageNum': 0, 'pageSize': 100},
          fromJson: (e) {
            List listMap = e['records'];
            return listMap.map((obj) {
              return ShopEvaluateEntity.fromJson(
                Map<String, dynamic>.from(obj),
              );
            }).toList();
          },
        ) ??
        [];
  }

  // 轮播图页面改变
  void onBannerPageChanged(int index) {
    currentBannerIndex.value = index;
  }

  // 点击媒体项
  void onMediaTap(int index) {
    // 获取所有图片URL
    List<String> imageUrls = mediaList.map((e) => e.getPicUrl()).toList();

    // 跳转到图片查看页面
    Get.toNamed(
      Routes.IMAGE_VIEWER,
      arguments: {'imageUrls': imageUrls, 'initialIndex': index},
    );
  }

  // 点击3D展示图片
  void on3DImageTap(int index) {
    // 获取所有3D图片URL
    List<String> imageUrls = product3DImages.map((e) => e.getPicUrl()).toList();

    // 跳转到图片查看页面
    Get.toNamed(
      Routes.IMAGE_VIEWER,
      arguments: {'imageUrls': imageUrls, 'initialIndex': index},
    );
  }

  // 点击商品介绍图片
  void onIntroImageTap(int index) {
    // 获取商品介绍图片URL
    List<String> imageUrls = shopDetailDetail?.getIntroduceImages() ?? [];

    if (imageUrls.isNotEmpty) {
      // 跳转到图片查看页面
      Get.toNamed(
        Routes.IMAGE_VIEWER,
        arguments: {'imageUrls': imageUrls, 'initialIndex': index},
      );
    }
  }

  // 关闭商品讲解悬浮窗
  void closeExplanationPopup() {
    isExplanationVisible.value = false;
  }

  // 切换评价类型
  void switchReviewType(String type) {
    selectedReviewType.value = type;
    // TODO: 根据类型筛选评价数据
  }

  // 切换收藏状态
  void toggleFavorite() {
    isFavorited.value = !isFavorited.value;
    ToastUtil.show(isFavorited.value ? '已收藏' : '已取消收藏');

    // 调用收藏接口
    if (isFavorited.isTrue) {
      app.http.request(
        method: Method.post,
        path: '/api/mall/saveProductFavorite',
        params: dio.FormData.fromMap({
          'productId': productId,
          'userId': app.getUser()?.id,
        }),
        fromJson: (e) => ApiResponse.fromJson(e),
      );
    }
  }

  // 进入店铺
  void enterStore() {
    // TODO: 跳转到店铺页面
    Get.snackbar('提示', '进入店铺');
  }

  // 开始聊天
  void startChat() {
    // TODO: 跳转到聊天页面
    Get.snackbar('提示', '开始聊天');
  }

  // 进入购物车
  void enterCart() {
    Get.toNamed(Routes.CART);
  }

  // 加入购物车
  void addToCart() {
    _showSpecModal('cart');
  }

  // 立即购买
  void buyNow() {
    _showSpecModal('buy');
  }

  // 显示规格选择弹窗
  void _showSpecModal(String type) {
    if (shopDetailEntity == null) return;

    // 创建模拟规格数据
    final specGroups = [
      ProductSpecGroup(
        name: '颜色',
        options: [
          ProductSpecOption(name: '无键盘托 全白', value: 'white_no_tray'),
          ProductSpecOption(name: '无键盘托 全黑', value: 'black_no_tray'),
          ProductSpecOption(name: '无键盘托 白架+黑面', value: 'white_frame_black_top'),
          ProductSpecOption(name: '有键盘托 全白', value: 'white_with_tray'),
          ProductSpecOption(name: '有键盘托 全黑', value: 'black_with_tray'),
          ProductSpecOption(
            name: '有键盘托 白架+黑面',
            value: 'white_frame_black_top_tray',
          ),
        ],
      ),
      ProductSpecGroup(
        name: '尺寸',
        options: [
          ProductSpecOption(name: '80*60*75', value: '80x60x75'),
          ProductSpecOption(name: '100*60*75', value: '100x60x75'),
        ],
      ),
    ];

    // 先创建控制器并初始化数据
    Get.put(ProductSpecModalController());
    final controller = Get.find<ProductSpecModalController>();
    controller.initModal(
      name: shopDetailEntity?.skuName ?? '',
      image: mediaList.first.getPicUrl(),
      price: shopDetailEntity?.salesPrice.toString() ?? '0',
      type: type,
      specs: specGroups,
    );

    // 显示弹窗
    Get.bottomSheet(
      const ProductSpecModalView(),
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
    );
  }

  // 返回按钮
  void onBackTap() {
    Get.back();
  }

  // 分享按钮
  void onShareTap() {
    // TODO: 实现分享功能
    Get.snackbar('提示', '分享商品');
  }
}
